package com.qishanor.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qishanor.framework.util.R;
import com.qishanor.system.mapper.SysUserMapper;
import com.qishanor.system.mapper.SysUserRoleMapper;
import com.qishanor.system.model.SysUser;
import com.qishanor.system.model.SysUserRole;
import com.qishanor.system.model.dto.SysUserDto;
import com.qishanor.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ExitCodeEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description: 用户表 服务实现类
 * @author: 周振林
 * @date: 2022-04-08
 * @Copyright: 博客：http://www.zhouzhenlin.com - 沉淀、分享、成长、让自己和他人都有所收获
 **/

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public SysUser login(String username, String password) {
        SysUser sysUser=baseMapper.selectOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUsername,username).eq(SysUser::getPassword,password));
        if(ObjectUtil.isEmpty(sysUser)){
            throw new RuntimeException("用户或密码错误");
        }
        return sysUser;
    }

    @Override
    public Page pageBy(Page page, SysUserDto sysUserDto) {

        return baseMapper.pageBy(page,sysUserDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveUser(SysUserDto sysUserDto) {
        SysUser user=new SysUser();
        BeanUtil.copyProperties(sysUserDto,user);
        baseMapper.insert(user);

        //保存角色
        sysUserDto.getRoleIds().forEach(roleId->{
            SysUserRole sysUserRole=new SysUserRole().setUserId(user.getId()).setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        });
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUser(SysUserDto sysUserDto) {
        SysUser user=new SysUser();
        BeanUtil.copyProperties(sysUserDto,user);
        baseMapper.updateById(user);

        //保存角色
        sysUserRoleMapper.delete(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getUserId,user.getId()));
        sysUserDto.getRoleIds().forEach(roleId->{
            SysUserRole sysUserRole=new SysUserRole().setUserId(user.getId()).setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        });
        return Boolean.TRUE;
    }


}
